<?php
class Product_Service_Offshelf
{
	public static function getPrintOrders($orders_code,$category,$orderType,$customerID,$type='*',$page=1,$pageSize=0,$orderBy=''){
		$orderModel = new Order_Model_Order();
		$orders = $orderModel->getByCategoryAndOrderType($orders_code,$category,$orderType,$customerID,$type,$page,$pageSize,$orderBy);
		return $orders;
	}
	
	public static function getPrintOrdersNew($condisiton,$type='*',$page=1,$pageSize=0,$orderBy=''){
		$orderModel = new Order_Model_Order();
		$orders = $orderModel->getByCategoryAndOrderTypeNew($condisiton,$type,$page,$pageSize,$orderBy);
		return $orders;
	}
		
	public static function printOrders($orderCodes,$members){
	
		$result = array();
		$category = "";
		
		//单号
		$opCode = self::generateCode();
		//先创建下架单 避免产生重复下架单
		$session = new Zend_Session_Namespace('userAuth');
		$user_id=$session->userID;     //操作人
		$pickRow = array(
				"op_code" => $opCode,
				"op_creater_id" => $user_id,
				"op_order_cnt" => 0,
				"op_product_cnt" => 0,
				"op_status" => 0,//配货单状态 未完成
				"op_create_date" => date("Y-m-d H:i:s"),
		);
		$opModel = new Product_Model_OrderPickup();
		$op_id = $opModel->create($pickRow);
		
		$splitArgs = 7;	//一个订单n个产品，分多页，每页最多显示$splitArgs个产品 
		$batch_count = 0;
		$orderlist = array();
		$errlist = array();
		$productCnt = 0;
		foreach($orderCodes as $orderCode){
			$orderProcess = new Order_Service_OrderProccess($orderCode);
			$order = $orderProcess->printOrder($opCode,$orderCode);

			if(isset($order['err'])){
				$errlist[] = $order;
			}else{
				ksort($order['product_bantch']);//批次货架排序
			
				foreach($order['product_bantch'] as $v_){						
					$order['ws_code']=$v_['ws_code'];//取得第一个产品的货架
					break;
				}
				$customer = Customer_Service_Customer::getByCustomerId($order['customer_id']);
				if($customer['customer_logo']){
					$order["customer_logo"] =  "/product/product/view-img/customer_id/".$order['customer_id']."/pa_path/".$customer['customer_logo']."";
				}
				$order["customer_intro"] = $customer['customer_intro'];
				
				
				$batch_count += count($order['product_bantch']);
				$orderlist[$order['ws_code'].$order['orders_code']] = $order;
				
				// 				$result["orders"][$order['ws_code']."__".$order['order_id']] = $order;
				$category == ""?$category = $order["order_product"][0]['category']:"";
				$productCnt += $order['productCnt'];
			}
			
			
		}
		
		ksort($orderlist);//货架排序
		$sort = 1;//订单排序更新
		foreach($orderlist as $k=>$v){
			$row['order_print_id'] = $sort++;
			Order_Service_Order::updateByOrdersCode($row,$v['orders_code']);
		}
		$orderlist_chunk = array();
		if($members){
			shuffle($members);//打乱数组
		}
			
		if(count($orderlist)>0){
			//配货员分配 start
			$membersCount = count($members);
			if($membersCount){
				// 			$loop = $batch_count%$membersCount==0?($batch_count/$membersCount):($batch_count/$membersCount+1);
				$avg = round($batch_count/$membersCount);//四舍五入
				$avg = $avg<1?1:$avg;
					
				// 			$clone = $orderlist;
				// 			$first = array_shift($clone);
				// 			$temp_code = $first['orders_code'];
				$temp_code = "";

				$step = 0;
				$membersPoint = 0;
				$shelfUser = array();
				foreach($orderlist as $k=>$v){
					if($step>=($avg*($membersPoint+1))&&$v['orders_code']!=$temp_code){
						$membersPoint++;
						$membersPoint = $membersPoint<$membersCount?$membersPoint:$membersCount-1;
					}

					$peihuoUser = explode('_', $members[$membersPoint]);
					$pickupUserId = $peihuoUser[0];
					$orderlist[$k]['peihuo'] = $peihuoUser[1];



					$temp_code = $v['orders_code'];
					$step = $step+count($v['product_bantch']);
					$updateRow = array('pickup_user_id'=>$pickupUserId);//更新订单配货人
					Order_Service_Order::updateByOrdersCode($updateRow,$v['orders_code']);



					$chunk = array_chunk($v['product_bantch'],$splitArgs);//每页最多9个产品
					foreach($chunk as $k0=>$v0){
						$v['product_batch'] = $v0;
						$v['page'] = $k0;
						if(isset($peihuoUser[1])){
							$v['peihuo'] = $peihuoUser[1];
						}else{
							$v['peihuo']='';
						}
							
						$orderlist_chunk[] =$v;
					}
				}
			}else{
					
				foreach($orderlist as $k=>$v){
					$chunk = array_chunk($v['product_bantch'],9);//每页最多9个产品
					foreach($chunk as $k0=>$v0){
						$v['product_batch'] = $v0;
						$v['page'] = $k0;
						$v['peihuo']='';
						$orderlist_chunk[] =$v;
					}
				}
			}
			//配货员分配 end


		}
		
		$result["orders"]=$orderlist_chunk;
		$result["err_orders"]=$errlist;
		$result["orders_count"]=count($orderlist);
		$result['category'] = $category;
		$result['code'] = $opCode;
		$result['date'] = date("Y-m-d");
		$result['admin'] = $session->name;
			
		if(count($orderlist)>0){//有成功订单，更新下架单
			//更新下架单
			$pickRow = array(
					"op_order_cnt" => count($orderlist),
					"op_product_cnt" => $productCnt,
					"op_status" => 0,//配货单状态 未完成
					"op_create_date" => date("Y-m-d H:i:s"),
			);
			$opModel = new Product_Model_OrderPickup();
			$opModel->update($pickRow,$op_id);
				
		}else{//无成功订单，删除下架单
			$opModel = new Product_Model_OrderPickup();
			$opModel->delete($op_id);
		}
				

		return $result;
	}
	
	public function my_compare($a, $b) {
		if ($a[1] < $b[1])
			return -1;
		else if ($a[1] == $b[1])
			return 0;
		else
			return 1;
	}
	
	
	/*
	 * $orderCodes array 订单号 
	 * $members array 配货员 */
	public static function hotFastPrintOrdersNew($orderCodes,$members){
		$result = array();
		$category = "";
	
		//单号
		$opCode = self::generateCode();
		//先创建下架单 避免产生重复下架单
		$session = new Zend_Session_Namespace('userAuth');
		$user_id=$session->userID;     //操作人
		$pickRow = array(
				"op_code" => $opCode,
				"op_creater_id" => $user_id,
				"op_order_cnt" => 0,
				"op_product_cnt" => 0,
				"op_status" => 0,//配货单状态 完成
				"op_create_date" => date("Y-m-d H:i:s"),
		);
		$opModel = new Product_Model_OrderPickup();
		$op_id = $opModel->create($pickRow);
		
		
		$productCnt = 0;
		$err = array();
		$orderlist = array();//成功订单
		$errlist = array();//失败订单
		$orderlist_distinct = array();
		$batch_count = 0;
		$bantchList = array();
		foreach($orderCodes as $orderCode){
			$orderProcess = new Order_Service_OrderProccess($orderCode);
			$order = $orderProcess->hotFastPrintOrderSingleNew($opCode);
// 			print_r($order);exit;
			if($order['op_status']==1){
				$orderlist_distinct[] = $order;
				$productCnt += $order['productCnt'];
				$batch_count += count($order['product_bantch']);
				
				ksort($order['product_bantch']);//产品批次按照货架排序
				$chunk = array_chunk($order['product_bantch'],5);//产品5个一页
				if(count($chunk)>1){//第一个和最后一个互换
					$chunk = array_reverse($chunk,true);
					$temp = $chunk[0];
					$chunk[0] = $chunk[count($chunk)-1];
					$chunk[count($chunk)-1] = $temp;
						
				}
	
				$count = 0;
				$order['page'] = 0;
				foreach($chunk as $k=>$v){
					$order['product_bantch'] = $v;
					$order['page'] = $k;
					$orderlist[$order['ws_code']."__".$order['order_id']."_".$count] =  $order;//订单货架作为键名
					$count++;
				}
				//更新订单打印时间
				$orderRow = array(
					"print_time" => date("Y-m-d H:i:s"),
				);				
				Order_Service_Order::update($orderRow,$order['order_id']);//更新订单打印时间
	
			}else{
				$errlist[] = $order;
			}
		}
		ksort($orderlist);//货架排序
		$sort = 1;//订单排序更新
		foreach($orderlist as $k=>$v){
			$row['order_print_id'] = $sort++;
			Order_Service_Order::updateByOrdersCode($row,$v['orders_code']);
		}
		
		if($members){
			shuffle($members);//打乱数组
		}
		
		if(count($orderlist)>0){
			//配货员分配 start
			$membersCount = count($members);			
			
			if($membersCount){
				$avg = round($batch_count/$membersCount);//四舍五入
				$avg = $avg<1?1:$avg;
				
				// 			$clone = $orderlist;
				// 			$first = array_shift($clone);
				// 			$temp_code = $first['orders_code'];
				$temp_code = "";
					
				$step = 0;
				$membersPoint = 0;
				$shelfUser = array();
				
				foreach($orderlist as $k=>$v){
					if($step>=($avg*($membersPoint+1))&&$v['orders_code']!=$temp_code){
						$membersPoint++;
						$membersPoint = $membersPoint<$membersCount?$membersPoint:$membersCount-1;
					}					
					$peihuoUser = explode('_', $members[$membersPoint]);
					$pickupUserId = $peihuoUser[0];
					$orderlist[$k]['peihuo'] = $peihuoUser[1];				
				
					$temp_code = $v['orders_code'];
					$step = $step+count($v['product_bantch']);
				
					$updateRow = array('pickup_user_id'=>$pickupUserId);//更新订单配货人
					Order_Service_Order::updateByOrdersCode($updateRow,$v['orders_code']);
				
				}
			}else{
				foreach($orderlist as $k=>$v){
					$orderlist[$k]['peihuo'] = '';				
				}
			}
			
			//配货员分配 end
		}
		
		
		
		$result['code'] = $opCode;
		$result['date'] = date("Y-m-d");
		$result['admin'] = $session->name;
		
		$result["orders_distinct"] = $orderlist_distinct;
		$result["orders_count"] = count($orderlist_distinct);
		$result["orders"] = $orderlist;
		$result["errors"] = $errlist;
	
		if(count($orderlist)>0){//有成功订单，更新下架单
			//更新下架单
			$pickRow = array(
					"op_order_cnt" => count($orderCodes),
					"op_product_cnt" => $productCnt,
					"op_status" => 1,//配货单状态 完成
					"op_create_date" => date("Y-m-d H:i:s"),
			);
			$opModel = new Product_Model_OrderPickup();
			$opModel->update($pickRow,$op_id);
				
		}else{//无成功订单，删除下架单			
			$opModel = new Product_Model_OrderPickup();
			$opModel->delete($op_id);				
		}
		
		
// 		print_r($orderlist_distinct);exit;
		return $result;
	}
	
	
	//生成下架单号
	public static function generateCode(){
		$sequence = "001";
		$offShelfModel = new Product_Model_OrderPickup();
		$offShelfs = $offShelfModel->getMaxByCurrentDate()->toArray();
		if(!empty($offShelfs)){
			$currentCode = current($offShelfs);
			$currentCode = substr($currentCode['op_code'],-3);
			$sequence = str_pad($currentCode + 1,3,"0",STR_PAD_LEFT);
		}
		$code = "U".date("ymd").$sequence;
		return $code;
	}
}